<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="false"
    :okAuth="'inspectionmanag:inEnterpriseTask:edit'"
    @register="registerDrawerDetail"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" />
    <!-- 任务类型选择 -->
    <div class="timeRange">
        <div v-if="inputFormData === 'INSPECTION'">
          <!-- 默认时间和自定义时间按钮 -->
          <div>
            <a-button
              :class="{ 'active': timeSelection === 'default' }"
              @click="handleTimeSelectionChange('default')"
            >
              默认时间
            </a-button>
            <a-button
              :class="{ 'active': timeSelection === 'custom' }"
              @click="handleTimeSelectionChange('custom')"
            >
              自定义时间
            </a-button>
          </div>
          <!-- 显示默认时间 -->
          <div v-if="timeSelection === 'default'" class="default-time-wrapper">
            <TimeRangePicker
              v-model:value="defaultTimeRange1"
              format="HH:mm"
              show-time
              :placeholder="['任务开始', '任务结束']"
              disabled
              :style="{ width: customTimeRangeWidth }"
            />
            <TimeRangePicker
              v-model:value="defaultTimeRange2"
              format="HH:mm"
              show-time
              :placeholder="['任务开始', '任务结束']"
              disabled
              :style="{ width: customTimeRangeWidth }"
            />
          </div>
        </div>
        <!-- 显示自定义时间段选择器 -->
        <div v-if="timeSelection === 'custom'" ref="customTimeRangeWrapper">
          <div id="custom-time-range-wrapper" v-for="(timeRange, index) in timeRanges" :key="index">
            <TimeRangePicker
              v-model:value="timeRanges[index]"
              format="HH:mm"
              show-time
              disabled
              :placeholder="['任务开始', '任务结束']"
            />
            <!-- <a-button type="primary" danger @click="deleteTimeRange(index)">删除</a-button> -->
          </div>
          <!-- <a-button id="add-time-range-btn" type="primary" @click="addTimeRange">增加时段</a-button> -->
        </div>
    </div>
  </BasicDrawer>
</template>

<script lang="ts" setup name="ViewsInspectionmanagInEnterpriseTaskForm">
import { ref, unref, computed, watch, onMounted } from 'vue';
import { TimeRangePicker, Button } from 'ant-design-vue';
import { useI18n } from '/@/hooks/web/useI18n';
import { useMessage } from '/@/hooks/web/useMessage';
import { router } from '/@/router';
import { Icon } from '/@/components/Icon';
import { BasicForm, FormSchema, useForm } from '/@/components/Form';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import { inEnterpriseTaskListData, InEnterpriseTask, inEnterpriseTaskSave, inEnterpriseTaskForm } from '/@/api/inspectionmanag/inEnterpriseTask';
import { Office, officeTreeData, officeListData, officeTreeDataList } from '/@/api/sys/office';
import { roleListData } from "/@/api/sys/role";
import { unitRegionListData } from "/@/api/unitmanage/unitRegion";
import dayjs from 'dayjs';

const emit = defineEmits(['success','register']);

const regionEnterpriseCode = ref<number>();
// 初始选择为自定义时间
const timeSelection = ref<string>('custom');
const { t } = useI18n('inspectionmanag.inEnterpriseTask');
const { showMessage } = useMessage();
const { meta } = unref(router.currentRoute);
const record = ref<InEnterpriseTask>({} as InEnterpriseTask);
const timeRanges = ref<any[]>([]);
// 自定义时间组件宽度
const customTimeRangeWidth = ref('');
// 表单任务类型数据
const inputFormData = ref();
const dataInputFormData=ref()

// 默认时间范围
const defaultTimeRange1 = ref([dayjs('00:00', 'HH:mm'), dayjs('12:00', 'HH:mm')]);
const defaultTimeRange2 = ref([dayjs('12:01', 'HH:mm'), dayjs('23:59', 'HH:mm')]);

watch(timeRanges, () => {
  console.log('时间', timeRanges.value);
});

const getTitle = computed(() => ({
  icon: meta.icon || 'i-ant-design:book-outlined',
  value: record.value.isNewRecord? t('详情') : t('详情'),
}));

// 响应式获取enterpriseCode
const TaskEenterpriseCode=ref()
const regionParams=computed(()=>{
  const enterpriseId=TaskEenterpriseCode.value
  console.log('regionParams.enterpriseId',enterpriseId)
  return enterpriseId
})
console.log('regionParams',regionParams)


const inputFormSchemas: FormSchema[] = [
  {
    label: t('任务名称'),
    field: 'name',
    component: 'Input',
    componentProps: {
      maxlength: 255,
      disabled:true
    },
    required: true,
  },
  {
    label: t('所属企业名称'),
    field: 'enterpriseCode',
    fieldLabel: "enterpriseName",
    component: 'TreeSelect',
    componentProps: {
      maxlength: 255,
      api: officeTreeData,
      params: {},
      onChange: (officeCode, officeName) => {
        record.value.enterpriseCode = officeCode;
        record.value.enterpriseName = officeName;
        TaskEenterpriseCode.value=officeCode;
        console.log('TaskEenterpriseCode',TaskEenterpriseCode.value);
      
      },
      allowClear: true,
      disabled:true
    },
  },
  {
    label: t('区域名称'),
    field: 'regionId',
    fieldLabel: "regionName",
    component: 'Select',
    componentProps: {
      api: unitRegionListData,
      resultField: "list",
      disabled:true,
      params:{
        enterpriseId:regionParams
      },
      fieldNames:{
        label: "name",
        value: "id"
      }
      
    }
  },
  {
    label: t('角色名称'),
    field: 'roleName',
    fieldLabel: "roleName",
    component: 'Select',
    componentProps: {
      maxlength: 255,
      api: roleListData,
      params: {

      },
      onChange: (id, roleName) => {
        record.value.roleCode = id;
        record.value.roleName = roleName;
      },
      resultField: "list",
      fieldNames: {
        label: "roleName",
        value: "id"
      },
      allowClear: true,
      disabled:true
    },
  },
  {
    label: t('任务要求'),
    field: 'remark',
    component: 'Input',
    componentProps: {
      maxlength: 255,
      disabled:true
    },
  },
  {
    label: t('任务内容'),
    field: 'content',
    component: 'InputTextArea',
    colProps: { md: 24, lg: 24 },
    componentProps:{
      disabled:true
    }
  },
  {
    label: t('任务类型名称'),
    field: 'taskTypeCode',
    fieldLabel: "taskTypeName",
    component: 'Select',
    componentProps: {
      maxlength: 40,
      dictType: 'task_type',
      onChange: (dict_value) => {
        inputFormData.value = dict_value;
        console.log('inputFormData.value',inputFormData.value);
      },
      resultField: "list",
      immediate: true,
      allowClear: true,
      disabled:true
    },
  },
];

const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 120,
  schemas: inputFormSchemas,
  baseColProps: { md: 24, lg: 12 },
});

const [registerDrawerDetail, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  setDrawerProps({ loading: true });
  await resetFields();
  const res = await inEnterpriseTaskForm(data);
  record.value = (res.inEnterpriseTask || {}) as InEnterpriseTask;
  record.value.__t = new Date().getTime();
  setFieldsValue(record.value);
  inputFormData.value = { ...record.value };
  // 处理从后端获取的时间段数据
  if (record.value.timeRange) {
    try {
      const parsedTimeRange = JSON.parse(record.value.timeRange);
      timeRanges.value = Object.values(parsedTimeRange).map(range => {
        const [start, end] = range.split('-');
        const startDate = dayjs(`2000-01-01T${start}:00`);
        const endDate = dayjs(`2000-01-01T${end}:00`);
        return [startDate, endDate];
      });
      console.log('解析时间段数据:', timeRanges.value);
    } catch (error) {
      console.error('解析时间段数据出错:', error);
    }
  }
  setFieldsValue(record.value);
  setDrawerProps({ loading: false });
});

function formatTime(date: Date): string {
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${hours}:${minutes}`;
}

async function handleSubmit() {
  try {
    let data = await validate();
    let timeRangeObj: Record<string, string> = {};
    setDrawerProps({ confirmLoading: true });

    if (timeSelection.value === 'default') {
      const startTime1 = defaultTimeRange1.value[0].format('HH:mm');
      const endTime1 = defaultTimeRange1.value[1].format('HH:mm');
      const startTime2 = defaultTimeRange2.value[0].format('HH:mm');
      const endTime2 = defaultTimeRange2.value[1].format('HH:mm');
      timeRangeObj = {
        value1: `${startTime1}-${endTime1}`,
        value2: `${startTime2}-${endTime2}`
      };
    } else {
      timeRanges.value.forEach((range, index) => {
        const startTime = range[0]? dayjs(range[0]).format('HH:mm') : null;
        const endTime = range[1]? dayjs(range[1]).format('HH:mm') : null;
        if (startTime && endTime) {
          timeRangeObj[`value${index + 1}`] = `${startTime}-${endTime}`;
        }
      });
    }

    const timeRangeJson = JSON.stringify(timeRangeObj);
    const params: any = {
      isNewRecord: record.value.isNewRecord,
      tid: record.value.tid,
      roleCode: record.value.roleCode,
      // taskTypeCode: record.value.taskTypeCode,
      timeRange: timeRangeJson,
    };
    const res = await inEnterpriseTaskSave(params, data);
    showMessage(res.message);
    setTimeout(closeDrawer);
    emit('success', data);
  } catch (error: any) {
    if (error && error.errorFields) {
      showMessage(error.message || t('common.validateError'));
    }
    console.log('error', error);
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}

// 删除动态时段
const deleteTimeRange = (index) => {
  if (Array.isArray(timeRanges.value)) {
    timeRanges.value.splice(index, 1);
  }
};

// 添加时段
const addTimeRange = () => {
  timeRanges.value.push([]);
};

// 处理时间选择改变
const handleTimeSelectionChange = (selection: string) => {
  timeSelection.value = selection;
  if (selection === 'default') {
    // 切换到默认时间时，清空自定义时间范围
    timeRanges.value = [];
  }
};

onMounted(() => {
  const customTimeRangeEl = unref(ref('customTimeRangeWrapper'));
  if (customTimeRangeEl) {
    const child = customTimeRangeEl.firstChild;
    if (child) {
      const width = window.getComputedStyle(child).width;
      customTimeRangeWidth.value = width;
    }
  }
  watch(timeSelection, (newValue) => {
    if (newValue === 'custom') {
      const customTimeRangeEl = unref(ref('customTimeRangeWrapper'));
      if (customTimeRangeEl) {
        const child = customTimeRangeEl.firstChild;
        if (child) {
          const width = window.getComputedStyle(child).width;
          customTimeRangeWidth.value = width;
        }
      }
    }
  });
});

watch(inputFormData, (newValue) => {
  // 当表单数据变化时，检查任务类型并更新显示
  if (newValue === 'InspectionTask') {
    // 确保默认时间相关元素显示
  } else {
    // 确保默认时间相关元素隐藏
    timeSelection.value = 'custom';
  }
}, { deep: true });
</script>

<style scoped lang="less">
.timeRange{
  margin-left: 120px;
  margin-bottom: 20px;
}
#custom-time-range-wrapper{
  margin-bottom: 10px;
}

#delete-time-range-btn{
  margin-left: 40px
}

#add-time-range-btn{
  margin-left: 0;
}
.active {
  background-color: #1890ff;
  color: white;
}

.default-time-wrapper {
  display: flex;
  flex-direction: column;
}
.ant-picker-disabled{
  width: 300px;
}
</style>